//
//  audio.m
//  audio
//
//  Created by user on 16/6/15.
//
//

#import "audio.h"
#import "MyAudioRecorder.h"
#import "VoiceConverter.h"
#import "MyHelper.h"
#import <Cordova/CDVPluginResult.h>

@interface audio()<NSURLConnectionDataDelegate>

@property(nonatomic, strong)MyAudioRecorder *myAudioRecorder;
@property(nonatomic, strong)AVAudioSession *avSession2;

@property (nonatomic, strong)AVAudioPlayer *localPlayer;
@property (nonatomic, strong)AVAudioPlayer *urlPlayer;

@property (copy, nonatomic) NSString *originWav;    //原wav文件名
@property (copy, nonatomic) NSString *convertAmr;   //转换后的amr文件名
@property (copy, nonatomic) NSString *originAmr;    //云上的amr
@property (copy, nonatomic) NSString *convertWav;   //amr转wav的文件名

@end

@implementation audio

#pragma mark - 开始录音 -
- (void)startRecordingAudio:(CDVInvokedUrlCommand *)command  {
    
    NSString *callbackId = [command callbackId];
    if (!self.myAudioRecorder) {
        self.myAudioRecorder = [[MyAudioRecorder alloc]init];
    }
    self.originWav = [MyHelper getCurrentTimeString];
    
    if (self.localPlayer && self.localPlayer.isPlaying) {
        [self.localPlayer pause];
    }
    if (self.urlPlayer && self.urlPlayer.isPlaying) {
        [self.urlPlayer pause];
    }
    [_myAudioRecorder beginRecordByFileName:_originWav];
    [self successCallback:@{@"message":@"开始录音"} callbackID:callbackId];
}

#pragma mark - 停止录音 -
-(void)stopRecordingAudio:(CDVInvokedUrlCommand *)command {

    NSString *callbackId = [command callbackId];
    NSString *json = [[command arguments] lastObject];
    NSNumber *time = [[MyHelper dictionaryWithJsonString:json]objectForKey:@"time"];
    
    [self.myAudioRecorder.avRecorder stop];
    NSString *wavPath = [MyHelper getPathByFileName:_originWav ofType:@"wav"];
    self.convertAmr = [MyHelper wavToAmrWithOriginWav:_originWav];
    NSString *amrPath = [MyHelper getPathByFileName:_convertAmr ofType:@"amr"];
    NSLog(@"====录音完成，文件路径: %@",wavPath);
//    NSLog(@"====录音完成，文件路径: %@  文件大小: %dkb",wavPath, [MyHelper getFileSize:wavPath]/1024);
    [self successCallback:@{@"message":@"停止录音", @"url":amrPath, @"wav":wavPath, @"time": time} callbackID:callbackId];
}

#pragma mark - 播放录音 -
-(void)playAudio:(CDVInvokedUrlCommand *)command {
    
    //声音外放
    NSError *err = nil;
    if (_myAudioRecorder.avSession) {  //本地
        [_myAudioRecorder.avSession setCategory :AVAudioSessionCategoryPlayback error:&err];
    } else { //url
        self.avSession2 = [MyHelper initAVAudioSession];
        [_avSession2 setCategory:AVAudioSessionCategoryPlayback error:&err];
    }
    
    NSString *callbackId = [command callbackId];
    NSString *json = [[command arguments] objectAtIndex:0];
    NSDictionary *dic = [MyHelper dictionaryWithJsonString:json];
    NSNumber *type = [dic objectForKey:@"from"];
    NSString *url = [dic objectForKey:@"url"];
    if ([type isEqualToNumber:@1]) { //from 为1 是本地, 2 url
        
        if (_originWav.length > 0) {
            self.localPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:[MyHelper getPathByFileName:_originWav ofType:@"wav"]] error:nil];
        }
        if (self.localPlayer.isPlaying) {
            [_localPlayer pause];
        }
        [_localPlayer play];
        
    } else {
        
        // 把云上的amr保存到本地
        [self saveAmrFromUrl:url];
        _convertWav = [MyHelper amrToWavWithOriginAmr:_originAmr];
        self.urlPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:[MyHelper getPathByFileName:_convertWav ofType:@"wav"]] error:nil];
        if (self.urlPlayer.isPlaying) {
            [_urlPlayer pause];
        }
        [_urlPlayer play];
    }
    [self successCallback:@{@"message":@"开始播放"}  callbackID:callbackId];
}

#pragma mark - 停止播放 -
-(void)stopAudio:(CDVInvokedUrlCommand *)command {

    NSString *callbackId = [command callbackId];
    if (self.localPlayer) {
        [self.localPlayer pause];
    }
    if (self.urlPlayer) {
        [self.urlPlayer pause];
    }
    [self successCallback:@{@"message":@"停止播放"} callbackID:callbackId];
}

#pragma mark -取消录音 -
- (void)cancelRecordingAudio:(CDVInvokedUrlCommand *)command {
    
    NSString *callbackId = [command callbackId];
    if (_myAudioRecorder.avRecorder.isRecording) {
        [_myAudioRecorder.avRecorder stop];
        [MyHelper deleteFileAtPath:[MyHelper getPathByFileName:_originWav ofType:@"wav"]];
    }
    [self successCallback: @{@"message":@"取消录音"} callbackID:callbackId];
}

#pragma mark - //保存amr文件到本地 -
- (void)saveAmrFromUrl:(NSString *)urlStr {
    
    if (urlStr.length > 17) {
        self.originAmr = [urlStr substringWithRange:NSMakeRange(urlStr.length - 17, 13)];
    }
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]];
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    NSString *fileDirectory = [[doc stringByAppendingPathComponent: _originAmr]stringByAppendingPathExtension:@"amr"];
    [data writeToFile:fileDirectory atomically:YES];
}

#pragma mark - 成功回调 -
- (void)successCallback:(NSDictionary *)dic callbackID: (NSString *)callbackID{
    
    NSString *sucStr = [MyHelper dictionaryToJson:dic];
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:sucStr];
    [self.commandDelegate sendPluginResult:result callbackId:callbackID];
}

#pragma mark - 失败回调 -
- (void)errorCallback:(NSString *)err callbackID: (NSString *)callbackID{
    
    CDVPluginResult *errorResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:err];
    [self.commandDelegate sendPluginResult:errorResult callbackId:callbackID];
}
@end
